package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.DistributorLevelRepository;
import cn.hd01.repository.entity.DistributorLevel;
import cn.hd01.service.DistributorLevelService;

@Service
public class DistributorLevelServiceImpl extends BaseServiceImpl<DistributorLevel, Integer> implements DistributorLevelService {

	private DistributorLevelRepository repository;
	
	@Autowired
	public DistributorLevelServiceImpl(DistributorLevelRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	@Cacheable(value="distributorLevel")
	public List<DistributorLevel> findAll() {
		return repository.findAll();
	}

	@Override
	@CacheEvict(value="distributorLevel", allEntries=true)
	public int updateDistributorLevel(DistributorLevel level) {
		int count = repository.updateDistributorLevel(level.getLevelName(), level.getRebateRate(), level.getId());
		return count;
	}
	
	@Override
	@CacheEvict(value="distributorLevel", allEntries=true)  
	public DistributorLevel save(DistributorLevel entity) {
		entity = repository.save(entity);
		return entity;
	}

	@Override
	public Page<DistributorLevel> findAll(final DistributorLevel distributorLevel,
			Pageable pageable) {
		if (distributorLevel == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<DistributorLevel>() {
			@Override
			public Predicate toPredicate(Root<DistributorLevel> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(distributorLevel.getLevelName())) {
					predicates.add(cb.like(r.get("levelName").as(String.class), "%" + distributorLevel.getLevelName() + "%"));
				}

				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}

}
